import { ref } from 'vue'
import { defineStore } from 'pinia'
import { getLoginUser as fetchLoginUser } from '@/api/userController'

export const useUserStore = defineStore('user', () => {
  // 定义初始状态，确保包含所有可能访问的属性
  const loginUser = ref({
    id: null,
    userAccount: '',
    userName: '',
    userAvatar: '',
    userProfile: '',
    userRole: '',
  })

  // 获取当前登录用户
  const getLoginUser = async () => {
    try {
      const res = await fetchLoginUser()
      if (res.data.code === 0) {
        if (res.data.data) {
          loginUser.value = {
            ...loginUser.value,
            ...res.data.data
          }
        }
      }
    } catch (error) {
      console.error('获取用户信息失败', error)
    }
  }

  // 设置登录用户
  const setLoginUser = (user: any) => {
    if (user) {
      loginUser.value = {
        ...loginUser.value,
        ...user
      }
    }
  }

  // 清除用户信息（登出时使用）
  const clearUser = () => {
    loginUser.value = {
      id: null,
      userAccount: '',
      userName: '',
      userAvatar: '',
      userProfile: '',
      userRole: '',
    }
  }

  return { loginUser, getLoginUser, setLoginUser, clearUser }
}, {
  persist: true
})
